package com.kum.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kum.domain.constant.ScriptConstant;
import com.kum.domain.dto.SysUserScriptDto;
import com.kum.domain.entity.SysScript;
import com.kum.domain.entity.SysUser;
import com.kum.utils.RedisUtils;
import com.kum.utils.RequestUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Package com.kum.service
 * @auhter 枯木Kum
 * @date 2021/6/19-7:19 PM
 * <p>...</p>
 */

@Log4j2
@Service
public class UserCacheService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SysScriptService scriptService;

    /**
     * 从数据库中读出用户已启用的脚本,将其缓存到Redis
     *
     * @param hostAddress
     * @param userId
     */
    public void putUserScriptMatchs(String hostAddress, String userId) {
        List<SysUserScriptDto> scriptDtos = scriptService.get(userId);
        Map<String, String> matchs = new HashMap<>();
        scriptDtos.forEach(script -> {
            if (script.getStatus().equals(ScriptConstant.enable)) {
                putScript(script);
                script.getMatch().forEach(m -> {
                    JSONObject object = new JSONObject();
                    object.put("scriptId", script.getId());
                    object.put("status", script.getStatus());

                    matchs.put(m.replaceAll(" ", ""), JSON.toJSONString(object));
                });
            }
        });
        redisUtils.putForDay(ScriptConstant.getScriptMatchCacheKey(hostAddress), JSON.toJSONString(matchs));
    }

    public Map<String, Object> getUserScriptMatchs(String hostAddress) {
        String matchText = redisUtils.get(ScriptConstant.getScriptMatchCacheKey(hostAddress));
        if (matchText == null || matchText.length() == 0) {
            return null;
        }

        return JSON.parseObject(matchText).getInnerMap();

    }

    public void putScript(SysScript script) {
        redisUtils.putForHour(ScriptConstant.getScriptCacheKey(script.getId()), JSON.toJSONString(script));
    }

    public SysScript getScript(String scriptId) {
        String scriptText = redisUtils.get(ScriptConstant.getScriptCacheKey(scriptId));
        if (scriptText == null || scriptText.length() == 0) {
            return null;
        }
        return JSON.parseObject(scriptText, SysScript.class);
    }

    public void refreshUserScriptCache() {
        SysUser loginUser = RequestUtils.getCurrentLoginUser();
        if (loginUser != null && loginUser.getHostAddress() != null && loginUser.getId() != null) {
            putUserScriptMatchs(loginUser.getHostAddress(), loginUser.getId());
            log.info("用户id: {} ,缓存已刷新", loginUser.getId());

        }
    }

}
